<template>
  <el-dialog
    :title="dialogMode === 'delete' ? '删除角色' : isNewRole ? '新增角色' : '编辑角色'"
    v-model="dialogVisible"
    :width="dialogMode === 'delete' ? '400px' : '500px'"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <!-- 编辑角色表单 -->
    <template v-if="dialogMode !== 'delete'">
      <div style="padding: 20px">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="80px"
          status-icon
        >
          <el-form-item label="角色标识" prop="role_id">
            <el-input
              v-model="formData.role_id"
              placeholder="请输入角色标识"
              :disabled="!isNewRole"
              maxlength="20"
              show-word-limit
            />
            <div class="form-item-tip" v-if="isNewRole">
              角色标识创建后不可修改，请谨慎填写
            </div>
          </el-form-item>
          <el-form-item label="角色名称" prop="role_name">
            <el-input
              v-model="formData.role_name"
              placeholder="请输入角色名称"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="角色备注" prop="comment">
            <el-input
              v-model="formData.comment"
              type="textarea"
              :rows="3"
              placeholder="请输入角色备注"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
    </template>

    <!-- 删除角色确认 -->
    <template v-else>
      <div class="delete-confirm">
        <el-icon class="warning-icon"><WarningFilled /></el-icon>
        <p>
          确定要删除角色
          <span class="role-name">{{ formData.role_name }}</span>
          吗？
        </p>
        <p class="warning-text">此操作不可逆，请谨慎操作！</p>
      </div>
    </template>

    <!-- 底部按钮 -->
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { WarningFilled } from '@element-plus/icons-vue'
import { addRoleApi, updateRoleApi, deleteRoleApi } from '@/api/modules/role'

interface RoleForm {
  _id: string
  role_id: string
  role_name: string
  comment: string
  [key: string]: any
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  // 统一使用一个属性来控制对话框模式: 'add'(新增), 'edit'(编辑), 'delete'(删除)
  type: {
    type: String,
    default: 'add',
    validator: (value: string) => ['add', 'edit', 'delete'].includes(value)
  },
  roleData: {
    type: Object,
    default: () => ({})
  },
  treeParent: {
    type: Object,
    default: () => ([])
  }
})

const emit = defineEmits(['update:visible', 'success', 'cancel'])

const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref()

// 计算属性：是否为新增角色
const isNewRole = computed(() => props.type === 'add')

// 计算属性：对话框模式
const dialogMode = computed(() => (props.type === 'delete' ? 'delete' : 'edit'))

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.keys(formData).forEach((key) => {
    formData[key] = ''
  })
}

// 表单数据
const formData = reactive<RoleForm>({
  _id: '',
  role_id: '',
  role_name: '',
  comment: ''
})

// 表单验证规则
const rules = {
  role_id: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: '角色标识只能包含字母、数字和下划线',
      trigger: 'blur'
    }
  ],
  role_name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  comment: [{ max: 100, message: '备注最多 100 个字符', trigger: 'blur' }]
}

// 监听visible属性变化
watch(
  () => props.visible,
  (val) => {
    dialogVisible.value = val
  }
)

// 监听roleData属性变化
watch(
  () => props.roleData,
  (val) => {
    if (val && Object.keys(val).length > 0) {
      Object.keys(formData).forEach((key) => {
        if (val[key] !== undefined) {
          formData[key] = val[key]
        }
      })
    } else {
      // 如果roleData为空，则清空表单数据（用于新增角色）
      resetForm()
    }
  },
  { immediate: true, deep: true }
)

// 监听dialogVisible变化，同步到父组件
watch(
  () => dialogVisible.value,
  (val) => {
    emit('update:visible', val)
  }
)

// 关闭弹窗时重置表单
const handleClosed = () => {
  resetForm()
}

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false
  emit('cancel')
}

// 确认操作
const handleConfirm = async () => {
  if (dialogMode.value !== 'delete') {
    // 编辑模式下需要表单验证
    if (!formRef.value) return

    await formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        loading.value = true
        try {
          // 根据是新增还是编辑调用不同的API
          if (isNewRole.value) {
            // 新增角色
            const res = await addRoleApi({ params: formData })
            if (res.errCode === 0) {
              dialogVisible.value = false
              emit('success', { ...formData, isNew: true })
            } else {
              ElMessage.error(res.errMsg || '新增角色失败')
            }
          } else {
            console.log(formData)

            // 编辑角色
            const res = await updateRoleApi({ params: formData })
            if (res.errCode === 0) {
              dialogVisible.value = false
              emit('success', { ...formData, isNew: false })
            } else {
              ElMessage.error(res.errMsg || '编辑角色失败')
            }
          }
        } catch (error) {
          console.error('操作失败', error)
          ElMessage.error('操作失败，请稍后重试')
        } finally {
          loading.value = false
        }
      }
    })
  } else {
    // 删除模式
    loading.value = true
    try {
      // 调用删除角色API
      const res = await deleteRoleApi({ params: formData })
      if (res.errCode === 0) {
        dialogVisible.value = false
        emit('success', { ...formData, isDeleted: true })
      } else {
        ElMessage.error(res.errMsg || '删除角色失败')
      }
    } catch (error) {
      ElMessage.error('删除失败，请稍后重试')
      console.error('删除失败', error)
    } finally {
      loading.value = false
    }
  }
}
</script>

<style lang="scss" scoped>
.delete-confirm {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;

  .warning-icon {
    font-size: 48px;
    color: #e6a23c;
    margin-bottom: 20px;
  }

  p {
    font-size: 16px;
    margin: 10px 0;
    text-align: center;

    .role-name {
      font-weight: bold;
      color: #409eff;
    }
  }

  .warning-text {
    color: #f56c6c;
    font-size: 14px;
    margin-top: 10px;
  }
}

.form-item-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
  color: red;
}
</style>
